
<!--body wrapper start-->
<div id="usersModel">
    <div class="row">
        <div class="col-sm-12">
            <section class="panel">
                <header class="panel-heading">
                    Editable Table
                    <span class="tools pull-right">
                        <a href="javascript:;" class="fa fa-chevron-down"></a>
                        <a href="javascript:;" class="fa fa-times"></a>
                     </span>
                </header>
                <div class="panel-body">
                    <div class="adv-table editable-table ">
                        <div class="clearfix">
                            <div class="btn-group">
                                <button id="editable-sample_new"
                                        class="btn btn-primary"
                                        @click="initAddModal()"
                                        type="button"
                                        data-toggle="modal"
                                        data-target="#modalAdd">
                                    Add New <i class="fa fa-plus"></i>
                                </button>
                            </div>
                            <div class="btn-group pull-right">
                                <button class="btn btn-default dropdown-toggle" data-toggle="dropdown">Tools <i class="fa fa-angle-down"></i>
                                </button>
                                <ul class="dropdown-menu pull-right">
                                    <li><a href="#">Print</a></li>
                                    <li><a href="#">Save as PDF</a></li>
                                    <li><a href="#">Export to Excel</a></li>
                                </ul>
                            </div>
                        </div>
                        <div class="space15"></div>
                        <table class="table table-striped table-hover table-bordered" id="editable-sample">
                            <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Points</th>
                                <th>Status</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>
<div th:replace="account/userAdd"></div>
<div th:replace="account/userEdit"></div>
<!--body wrapper end-->
<script>
    var usersVue = new Vue({
        el: "#usersModel",
        data: {
            user: {
                id: 0,
                createDate: "",
                userName: "",
                password: "",
                userImage: "",
                roles: [],
            },
            roles: [],
            search: {
                currentPage: 1,
                pageSize: 5,
                sort: "id",
                direction: "desc",
                keyword: "",
            },
            // 表格数据结构
            tableData: {
                draw: 0,
                recordsTotal: 0,
                recordsFiltered: 0,
                data: [],
            },
            defaultPageSize: 5,
        },
        methods: {
            // 行数据结构
            rowData: function (id, userName, password, userImage, createDate) {
                var row = {};
                row.id = id;
                row.userName = userName;
                row.password = password;
                row.userImage = userImage;
                row.createDate = createDate;
                row.operate = function () {
                    return (
                        "<a class='btn_editcolor' onclick='initModel(" +
                        id +
                        ")' data-toggle='modal' data-target='#modalEdit'>修改</a>&nbsp;&nbsp;" +
                        "<a class='btn_editcolor' onclick='deleteModel(" +
                        id +
                        ")'>删除</a>"
                    );
                };
                return row;
            },
            initDataTable: function (pageSize) {
                var self = this;
                self.dataTable = $("#modelTable").DataTable({
                    paging: true, //分页
                    serverSide: true, //开启后端分页
                    pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
                    pageLength: pageSize, //定义初始的页长
                    processing: true,
                    destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
                    lengthChange: true, //控制是否能够调整每页的条数
                    lengthMenu: [5, 10, 25, 50], // 控制页长
                    searching: true,
                    "data-show-refresh": true,
                    ordering: true,
                    order: [0, "desc"], // 默认第 0 列倒叙排列
                    autoWidth: true,
                    ajax: function (data, callback, settings) {
                        // 从data获取查询数据
                        var columIndex = data.order[0].column;
                        var direction = data.order[0].dir;
                        var sort = data.columns[columIndex].name;
                        pageSize = data.length == undefined ? pageSize : data.length;

                        self.search.currentPage = data.start / pageSize + 1;
                        self.search.pageSize = pageSize;
                        self.search.sort = sort;
                        self.search.direction = direction;
                        self.search.keyword = data.search.value;

                        $.ajax({
                            url: "/api/users",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(self.search),
                            success: function (rs) {
                                if (!rs) {
                                    layer.alert("请求出错，请稍后重试" + rs.errmsg, { icon: 2 });
                                    callback(self.tableData);
                                    return;
                                }
                                if (rs.list == null) {
                                    $("#moduleTable tbody tr").remove();
                                    $("#loading").remove();
                                    callback(self.tableData);
                                    return;
                                }
                                $("#loading").remove();
                                var rowsData = [];
                                $.each(rs.list, function (i, item) {
                                    //包装行数据
                                    var rowData = self.rowData(
                                        item.id,
                                        item.userName,
                                        item.password,
                                        item.userImage,
                                        item.createDate
                                    );
                                    // 将行数据放到数组里
                                    rowsData.push(rowData);
                                });
                                self.tableData.data = rowsData;
                                self.tableData.recordsTotal = rs.total;
                                self.tableData.recordsFiltered = rs.total;
                                callback(self.tableData);
                            },
                            error: function (data) {
                                layer.alert(data.responseText, { icon: 0 });
                            },
                        });
                    },
                    columns: [
                        //定义行数据字段
                        { data: "id", name: "id", sortable: true },
                        { data: "userName", name: "user_name", sortable: true },
                        { data: "password", name: "password", sortable: true },
                        { data: "userImage", name: "userImage", sortable: true },
                        { data: "createDate", name: "create_date", sortable: true },
                        { data: "operate", width: "80px", sortable: false },
                    ],
                });
            },
            initFileUpload: function () {
                var self = this;
                $("#uploadImage")
                    .fileinput({
                        uploadUrl: "/api/image/profile-big",
                        enctype: "multipart/form-data",
                        previewFileType: "image",
                        uploadAsync: true,
                        allowedFileExtensions: ["png", "jpg", "jpeg", "ico", "bmp", "gif"],
                        maxFileCount: 1,
                        maxFileSize: 3072,
                        minImageWidth: 50,
                        minImageHeight: 50,
                        maxImageWidth: 1000,
                        maxImageHeight: 1000,
                        msgFilesTooMany: "Upload file count({n} - {m})",
                        showCaption: false,
                        dropZoneEnabled: false,
                        showBrowse: true,
                        browseClass: "btn btn-primary",
                        uploadClass: "btn btn-info",
                        removeClass: "btn btn-danger",
                    })
                    .on("fileerror", function (event, data, msg) {
                        layer.alert("Upload file failed" + msg, { icon: 0 });
                    })
                    .on("fileuploaded", function (event, data) {
                        if (data.response.status == 200) {
                            self.user.userImage = data.response.data;
                        } else {
                            $(".fileinput-remove-button").click();
                        }
                        layer.alert(data.response.message, { icon: 0 });
                    })
                    .on("fileclear", function (event) {});
            },
            initRoles: function () {
                var self = this;
                $.ajax({
                    url: "/api/roles",
                    type: "get",
                    success: function (rs) {
                        self.roles = rs;
                    },
                    error: function () {
                        layer.alert("服务器错误", { icon: 0 });
                    },
                });
            },
            initAddModal: function () {
                this.user = {
                    id: 0,
                    createDate: "",
                    userName: "",
                    password: "",
                    userImage: "",
                    roles: [],
                };
            },
            addModel: function () {
                var self = this;
                self.user.roles = self.user.roles.map((item) => {
                    var role = {};
                    role.id = item;
                    return role;
                });
                console.log(self.user);
                $.ajax({
                    url: "/api/user",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(self.user),
                    success: function (rs) {
                        if (rs.status == 200) {
                            $("#modalAdd").modal("hide");
                            self.initDataTable(self.defaultPageSize);
                        } else {
                            layer.alert(rs.message, { icon: 0 });
                        }
                    },
                    error: function () {
                        layer.alert("服务器错误", { icon: 0 });
                    },
                });
            },
            initModel: function (id) {
                var self = this;
                $.ajax({
                    url: "/api/user/" + id,
                    type: "get",
                    success: function (rs) {
                        self.user = rs;
                        self.user.roles = self.user.roles.map((item) => {
                            return item.id;
                        });
                    },
                    error: function () {
                        layer.alert("服务器错误", { icon: 0 });
                    },
                });
            },
            updateModel: function () {
                var self = this;
                self.user.roles = self.user.roles.map((item) => {
                    var role = {};
                    role.id = item;
                    return role;
                });
                console.log(self.user);
                $.ajax({
                    url: "/api/user",
                    type: "put",
                    contentType: "application/json",
                    data: JSON.stringify(self.user),
                    success: function (rs) {
                        if (rs.status == 200) {
                            $("#modalEdit").modal("hide");
                            self.initDataTable(self.defaultPageSize);
                        } else {
                            layer.alert(rs.message, { icon: 0 });
                        }
                    },
                    error: function () {
                        layer.alert("服务器错误", { icon: 0 });
                    },
                });
            },
            deleteModel: function (id) {
                var self = this;
                bootbox.confirm("Are you sure?", function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/user/" + id,
                            type: "delete",
                            success: function (rs) {
                                if (rs.status == 200) {
                                    self.initDataTable(self.defaultPageSize);
                                } else {
                                    layer.alert(rs.message, { icon: 0 });
                                }
                            },
                            error: function (data) {
                                layer.alert(data.responseText, { icon: 0 });
                            },
                        });
                    }
                });
            },
        },
        created() {
            window.initModel = this.initModel;
            window.deleteModel = this.deleteModel;
        },
        mounted() {
            this.initDataTable(this.defaultPageSize);
            this.initFileUpload();
            this.initRoles();
        },
    });
</script>
